package com.yuezheng.modules.system.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuezheng.modules.system.service.ZabbixApi;
import com.yuezheng.modules.system.service.dto.ZabbixQueryCriteria;
import me.zhengjie.utils.AreacodeContant;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.HttpResponseUtils;
import me.zhengjie.utils.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by bruce on 19/7/11.
 */
@RestController
@CrossOrigin
@Configuration
@RequestMapping("/yuezheng")
public class ZabbixController {

    @Autowired
    private ZabbixApi zabbixApi;

    @Value("${zabbix.chinaid}")
    private String chinaid;

    private String pingseckey = "icmppingsec";
    private String INKEY = "net.if.in[ifInOctets.8]";
    private String OUTKEY = "net.if.out[ifOutOctets.8]";
    //Map<String,String> itemhostMap = new HashMap<>();  //主机item对应map
    Map<String,String> itemitemMap = new HashMap<>();
    Map<String,String> hostidNameMap = new HashMap<>();
    Map<String,String> nameHostidMap = new HashMap<>();

    String inKeyPattern = "Interface GigabitEthernet0/0/\\d+: Bits received";  //Pattern.compile();
    String outKeyPattern = "Interface GigabitEthernet0/0/\\d+: Bits sent" ; //Pattern.compile("Interface GigabitEthernet0/0/\\d+: Bits sent");

    @GetMapping(value = "/zabbix/hostgroup/get")
    public ResponseEntity hostGroupGet(HttpServletRequest request) {
        HashMap<String,Object> filter = new HashMap<String,Object>();
        filter.put("real_hosts",Boolean.TRUE);

        JSONArray array = zabbixApi.hostGroup_Get(filter);
        JSONArray result = new JSONArray();

        String fullFlag = request.getParameter("flag");

        for(Object obj: array) {
            JSONObject groupItem = new JSONObject();
            groupItem.put("groupid", ((JSONObject)obj).getIntValue("groupid"));
            String name = ((JSONObject)obj).getString("name");
            if(me.zhengjie.utils.StringUtils.isEmpty(fullFlag)) {
                if (name.startsWith("VIP-")) {
                    groupItem.put("name", name.substring(4));
                    result.add(groupItem);
                }
            }else{
                groupItem.put("name",name);
                result.add(groupItem);
            }
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @GetMapping(value = "/zabbix/alarms/get")
    public ResponseEntity CityAlarmsStats(ZabbixQueryCriteria criteria) {
        //获取机器组,包含机器,才有可能关联错误
        HashMap<String,Object> filter = new HashMap<String,Object>();
        filter.put("real_hosts",Boolean.TRUE);

        JSONArray array = zabbixApi.hostGroup_Get(filter);

        HashMap<Integer,String> groupidNameMap = new HashMap<Integer,String>(); //组id对应组名
        for(Object obj: array) {
            groupidNameMap.put( ((JSONObject)obj).getIntValue("groupid"),
                    ((JSONObject)obj).getString("name") );
        }

        //获取错误信息
        filter.clear();
        filter.put("selectHosts","extend");
        filter.put("selectGroups","extend");
        filter.put("filter",JSONObject.parse("{\"value\":1}"));
        if(!StringUtils.isEmpty(criteria.getGroupids()))
            filter.put("groupids",criteria.getGroupids());

        JSONArray result = new JSONArray();
        HashMap<Integer,Integer> areaCount = new HashMap<Integer,Integer>(); //地域对应的错误信息
        if(StringUtils.isEmpty(criteria.getParentCityCode()) || criteria.getParentCityCode().equals("0")) { // 默认取全中国的数据
            array = zabbixApi.trigger_Get(filter);
            for(Object obj: array) { //错误数据
                JSONObject trigger = (JSONObject)obj;
                JSONArray groupArray = trigger.getJSONArray("groups");
                for(Object group: groupArray){
                    String groupname = ((JSONObject)group).getString("name");  //组名
                    Integer areacode = AreacodeContant.getAreacode(groupname);
                    if(areacode!=null) {
                        areaCount.put(areacode,areaCount.getOrDefault(groupname,0)+1); //错误数量
                    }else{
                        if(groupname.equals("VIP-工商银行")) {
                            areaCount.put(330000,areaCount.getOrDefault(groupname,0)+1); //错误数量
                        }
                    }
                }
            }

            //返回结果
            for(HashMap.Entry<Integer,Integer> entry: areaCount.entrySet()) {
                if(entry.getKey()%10000==0) {  //省一级
                    JSONObject obj = new JSONObject();
                    obj.put("cityCode", entry.getKey());
                    obj.put("alarmCount", entry.getValue());
                    result.add(obj);
                }
            }
        } else { //省一级
            Integer parentCitycode = Integer.valueOf(criteria.getParentCityCode());  //省一级的编码
            array = zabbixApi.trigger_Get(filter);
            for(Object obj: array) { //错误数据
                JSONObject trigger = (JSONObject)obj;
                JSONArray groupArray = trigger.getJSONArray("groups");
                for(Object group: groupArray){
                    String groupname = ((JSONObject)group).getString("name");  //组名
                    Integer areacode = AreacodeContant.getAreacode(groupname);
                    if(areacode!=null) {
                        if((areacode/10000)==(parentCitycode/10000))
                            areaCount.put(areacode,areaCount.getOrDefault(groupname,0)+1); //错误数量
                    }else{
                        if(groupname.equals("VIP-工商银行") && parentCitycode==330000) {
                            areaCount.put(330100,areaCount.getOrDefault(groupname,0)+1); //错误数量
                        }
                    }
                }
            }

            //返回结果
            for(HashMap.Entry<Integer,Integer> entry: areaCount.entrySet()) {
                JSONObject obj = new JSONObject();
                obj.put("cityCode", entry.getKey());
                obj.put("alarmCount", entry.getValue());
                result.add(obj);

            }
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }


    @GetMapping(value = "/zabbix/alarms/host")
    public ResponseEntity CityAlarmHostsGet(ZabbixQueryCriteria criteria) {
        HashMap<String,Object> filter = new HashMap<String,Object>();
        filter.put("selectHosts","extend");
        filter.put("filter",JSONObject.parse("{\"value\":1}"));
        if(!StringUtils.isEmpty(criteria.getGroupids())){
            filter.put("groupids",criteria.getGroupids().split(","));
        }
        JSONArray triggerArray = zabbixApi.trigger_Get(filter);

        HashMap<Integer,Integer> hostPriorityMap = new HashMap<Integer,Integer>();

        for(Object _obj: triggerArray) {
            JSONObject object = (JSONObject) _obj;
            JSONArray hostsArray = (JSONArray)object.getJSONArray("hosts");
            if(hostsArray.size()>0) {
                Integer hostid = ((JSONObject)hostsArray.toArray()[0]).getInteger("hostid");
                hostPriorityMap.put(hostid,object.getInteger("priority"));
            }
        }

        filter.clear();
        filter.put("selectInterfaces","extend");
        if(!StringUtils.isEmpty(criteria.getGroupids())){
            filter.put("groupids",criteria.getGroupids().split(","));
        }
        filter.put("selectGroups","extend"); //加组信息
        JSONArray array = zabbixApi.host_Get(filter);  //带ip

        JSONArray result = new JSONArray();
        JSONArray result2 = new JSONArray();
        JSONArray result3 = new JSONArray();
        Integer cityCode= null;

        if(!StringUtils.isEmpty(criteria.getCityCode()))
            cityCode = Integer.valueOf(criteria.getCityCode()) ;  //城市代码

        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;
            JSONObject object = new JSONObject();
            JSONArray groupArray = hostObj.getJSONArray("groups");

            boolean flag = false ;
            for(Object group: groupArray){
                String groupname = ((JSONObject)group).getString("name");  //组名
                Integer areacode = AreacodeContant.getAreacode(groupname);
                if(areacode!=null) {
                    if(areacode.equals(cityCode))
                        flag = true;
                }else{
                    if(groupname.equals("VIP-工商银行") && cityCode.equals(330100)) {
                        flag = true;
                    }
                }
            }
            if(!flag)
                continue ; //特定城市才处理

            object.put("hostname",hostObj.getString("name"));
            JSONArray ipArray = (JSONArray)hostObj.getJSONArray("interfaces");
            if(ipArray.size()>0){
                object.put("ip", ((JSONObject)ipArray.toArray()[0]).getString("ip"));
            }else{
                object.put("ip","");
            }

            Integer priority = hostPriorityMap.get(hostObj.getInteger("hostid"));
            if(priority==null){
                object.put("status",1);
                result.add(object);
            }else{
                if(priority>=4){
                    object.put("status",3);
                    result3.add(object);
                }else{
                    object.put("status",2);
                    result2.add(object);
                }
            }
        }
        for(Object obj: result2){
            result.add(0,obj);
        }
        for(Object obj: result3){
            result.add(0,obj);
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }

    /**
     * 获取有问题主机，除了正常，不可用之外
     * @return
     */
    private Map<Integer, JSONObject> getStatus1Hosts(String hostids) {
        HashMap<String,Object> filter = new HashMap<String,Object>();
        //获取一般问题主机
        java.util.List<Integer> sererites = new ArrayList();
        sererites.add(1); sererites.add(2); sererites.add(3); //一般问题
        filter.put("severities", sererites.stream().toArray());
        JSONObject fObj = new JSONObject(); fObj.put("type",2); //snmp,其它不取
        filter.put("filter", fObj);

        if(hostids != null)
            filter.put("hostids",hostids);

        JSONArray arrayProblems = zabbixApi.host_Get(filter);  //获取带问题数据，正常及不可用之间
        HashMap<Integer, JSONObject> map = new HashMap();  //全部的主机
        for(Object _hostObj: arrayProblems) {
            JSONObject hostObj = (JSONObject) _hostObj;
            map.put(hostObj.getInteger("hostid"), hostObj);
        }
        return map;
    }

    /**
     * 获取所有主机（国家信息的数据)
     * @return
     */
    @GetMapping(value = "/zabbix/level1/get")
    public ResponseEntity level1Get() {
        HashMap<String,Object> filter = new HashMap<String,Object>();
        filter.put("selectInterfaces","extend");// 网卡
        filter.put("selectInventory",true); //资产
        JSONObject fObj = new JSONObject(); fObj.put("type",2); //snmp,其它不取
        filter.put("filter", fObj);
        JSONArray arrayAll = zabbixApi.host_Get(filter);  //获取全部数据

        //获取一般问题主机
        java.util.List<Integer> sererites = new ArrayList();
        sererites.add(1); sererites.add(2); sererites.add(3); //一般问题
        filter.put("severities", sererites.stream().toArray());
        JSONArray arrayProblems = zabbixApi.host_Get(filter);  //获取带问题数据，正常及不可用之间
        HashMap<Integer, JSONObject> map = new HashMap();  //全部的主机
        for(Object _hostObj: arrayProblems) {
            JSONObject hostObj = (JSONObject) _hostObj;
            map.put(hostObj.getInteger("hostid"), hostObj);
        }

        //全部数据开始组装
        JSONArray result = new JSONArray();
        for(Object _hostObj: arrayAll) {
            JSONObject hostObj = (JSONObject) _hostObj;

            JSONObject object = new JSONObject();
            object.put("name",hostObj.getString("name"));
            object.put("hostid",hostObj.getString("hostid"));
            //资产数据，主要取gps的

            Object inv = hostObj.get("inventory");
            if(inv instanceof JSONArray) {
                if(((JSONArray) inv).size() > 0) {
                    JSONObject inventory = hostObj.getJSONArray("inventory").getJSONObject(0);
                    object.put("location_lat", inventory.getString("location_lat"));
                    object.put("location_lon", inventory.getString("location_lon"));
                }
            } else {
                JSONObject inventory = hostObj.getJSONObject("inventory");
                object.put("location_lat", inventory.getString("location_lat"));
                object.put("location_lon", inventory.getString("location_lon"));
            }
            object.put("status", 0);
            //object.put("available","1");

            JSONArray interfaces = hostObj.getJSONArray("interfaces");
            if(interfaces.size() > 0) {
                JSONObject interface0 = (JSONObject)(interfaces.get(0));
                if(interface0.getInteger("available") == 2) {
                    object.put("status", 2); //不可用
                } else {
                    if(map.get(hostObj.getInteger("hostid")) != null) { //存在问题
                        object.put("status", 1); //存在问题
                    }
                }
                object.put("ip", interface0.getString("ip"));  //ip地址
                object.put("available", interface0.getString("available"));  //可用或不可用  1，2
            }
            result.add(object);
        }
        JSONObject entiry = new JSONObject();
        entiry.put("status", HttpStatus.OK.value());
        entiry.put("data",result);
        return new ResponseEntity(entiry, HttpStatus.OK);
    }

    /**
     * 获取非中国数据，本质上只有一个国家,不分页，导出使用
     * @param filter
     * @return
     */
    private void processNotChinaHisDataWithoutPage(HashMap<String,Object> filter,
                                                    String hostid,String timestart, String timeend,
                                                    HttpServletResponse response) {
        Map<String,String> itemhostMap = new HashMap<>();
        JSONArray array = zabbixApi.host_Get(filter);  //带ip

        JSONArray result = new JSONArray();
        Map<Integer,JSONObject> mapStatus1 = getStatus1Hosts(hostid);

        List<String> itemids = new ArrayList<>();  //itemid;

        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;

            JSONObject object = parseHostObject(hostObj,mapStatus1);
            hostidNameMap.put(hostid, hostObj.getString("name"));
            nameHostidMap.put(hostObj.getString("name"),hostid);

            //JSONObject net = new JSONObject();
            object.put("inbound","0.00%");
            object.put("outbound","0.00%");
            Integer base = getBandwidth(hostObj.getJSONArray("tags"));
            object.put("base",base);

            for(Object _obj: hostObj.getJSONArray("items")){
                JSONObject item = (JSONObject)_obj;
                //设置itemid与映射关系，后面使用
                String itemid = item.getString("itemid");
                itemhostMap.put(itemid, hostObj.getString("hostid"));

                if(item.getString("key_").equals("icmppingloss")) {
                    //System.out.println("icmppingloss itemid:" + item.getString("itemid") + item.getString("lastvalue"));
                    object.put("icmppingloss", item.getString("lastvalue")+"%");
                }
                if(item.getString("key_").equals(pingseckey)) {
                    //System.out.println("icmppingsec itemid:" + item.getString("itemid") + item.getString("lastvalue"));
                    object.put("icmppingsec",String.format(("%.0fms"),item.getFloat("lastvalue")*1000));
                    object.put("icmppingsecitem", item.getString("itemid"));
                    itemids.add(item.getString("itemid"));  //后面查询使用
                    itemitemMap.put(item.getString("itemid"), pingseckey);
                }

                if(item.getString("key_").equals(INKEY)) {
                    System.out.println(item.getString("key_") + item.getString("lastvalue"));
                    object.put("inbound",String.format("%.2f%%", (100*item.getFloat("lastvalue"))/1024/1024/base));
                    //object.put("base", base);
                    object.put("inbounditem", item.getString("itemid"));
                    itemids.add(item.getString("itemid"));  //后面查询使用
                    itemitemMap.put(item.getString("itemid"), INKEY);
                }

                if(item.getString("key_").equals(OUTKEY)) {
                    System.out.println(item.getString("key_") + item.getString("lastvalue"));
                    object.put("outbound",String.format("%.2f%%", (100*item.getFloat("lastvalue"))/1024/1024/base));
                    object.put("outbounditem", item.getString("itemid"));
                    //object.put("base", base);
                    itemids.add(item.getString("itemid"));  //后面查询使用
                    itemitemMap.put(item.getString("itemid"), OUTKEY);
                }
            }

            result.add(object);
        }
        //获取趋势数据
        filter.clear();
        filter.put("itemids", itemids);
        JSONArray trends = zabbixApi.trend_get(filter);

        HashMap<String,ArrayList<Float>> valueMap = new HashMap<>();
        for(Object _o: trends) {
            JSONObject trend = (JSONObject)_o;
            String itemid = trend.getString("itemid");
            String itemname = itemitemMap.get(itemid); //sec/in/out
            String key = String.format("%s_%s_%s", itemhostMap.get(itemid),itemid,itemname);
            ArrayList<Float> fList = valueMap.getOrDefault(key,new ArrayList<>());
            //fList.add(trend.getFloat("value_min"));
            //fList.add(trend.getFloat("value_max"));
            fList.add(trend.getFloat("value_avg"));
            valueMap.put(key,fList);
        }

        List<String> hostids = new ArrayList<>();
        hostids.add(hostid);
        processExcelData(result, valueMap, hostids, response, Long.valueOf(timestart), Long.valueOf(timeend));
    }

    /**
     * tag hostname: interface, from interface->hostname->hostid
     * @param value
     * @param array
     * @param nameHostidMap
     * @return
     */
    private String getHostidFromInterface(String value, JSONArray array, Map<String,String> nameHostidMap) {
        //for(Object _obj: hostObj.getJSONArray("tags")) {
        for(Object _obj: array) {
            JSONObject item = (JSONObject) _obj;
            if(value.equals(item.getString("value"))) {
                return nameHostidMap.getOrDefault(item.getString("tag"), "");
            }
        }
        return "";
    }

    /**
     * 获取中国数据
     * @param filter
     * @return
     */
    private void processChinaHisDataWithoutPage(HashMap<String,Object> filter,
                                              String timestart, String timeend,
                                              HttpServletResponse response) {
        filter.put("sortfield","host"); //排序
        JSONArray array = zabbixApi.host_Get(filter);  //带ip

        Map<Integer,JSONObject> mapStatus1 = getStatus1Hosts(null);

        List<String> itemids = new ArrayList<>();  //itemid;
        HashMap<String,String> itemidHostidMap = new HashMap<>();

        JSONObject ChinaObj = null;
        HashMap<String, JSONObject> result = new HashMap<>();
        SortedMap<Integer, String> sortedIds = new TreeMap<>();  //后续排序使用

        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;
            String hostid = hostObj.getString("hostid");
            String hostname = hostObj.getString("name");
            if(hostid.equals(chinaid)) {
                ChinaObj = hostObj;
            }
            JSONObject object = parseHostObject(hostObj, mapStatus1);
            sortedIds.put(Integer.valueOf(object.getString("ip").split("\\.")[3]),hostid);
            object.put("hostname", hostname);
            object.put("hostid", hostid);
            hostidNameMap.put(hostid, hostname);
            nameHostidMap.put(hostname,hostid);


            object.put("inbound","0.00%");
            object.put("outbound","0.00%");
            Integer base = getBandwidth(hostObj.getJSONArray("tags"));
            object.put("base",base);

            for(Object _obj: hostObj.getJSONArray("items")){
                JSONObject item = (JSONObject)_obj;
                //设置itemid与映射关系，后面使用
                String itemid = item.getString("itemid");
                itemidHostidMap.put(itemid, hostObj.getString("hostid"));

                if(item.getString("key_").equals(pingseckey)) {
                    //System.out.println("icmppingsec itemid:" + item.getString("itemid") + item.getString("lastvalue"));
                    object.put("icmppingsec",String.format(("%.0fms"),item.getFloat("lastvalue")*1000));
                    object.put("icmppingsecitem", item.getString("itemid"));
                    itemids.add(itemid);  //后面查询使用
                    itemitemMap.put(itemid, pingseckey);
                    itemidHostidMap.put(itemid,hostid);
                }
            }
            result.put(hostid,object);
        } //end of nonechina

        //中国对应items，取进出历史记录
        {
            JSONArray tags = ChinaObj.getJSONArray("tags");
            for(Object _obj: ChinaObj.getJSONArray("items")) {
                JSONObject item = (JSONObject) _obj;
                String key = item.getString("name");
                String itemid = item.getString("itemid");
                if (Pattern.matches(inKeyPattern, key)) { //item.getString("key_").equals(inkey)) {
                    String port = key.substring(
                            key.lastIndexOf("/")+1,
                            key.indexOf(":"));
                    String hostid = getHostidFromInterface(port, tags, nameHostidMap); //获取主机id

                    JSONObject object = result.get(hostid);
                    if(object != null) {
                        System.out.println(hostid+"_"+itemid+"_"+key + item.getString("lastvalue"));
                        Integer base = object.getInteger("base");
                        object.put("inbound", String.format("%.2f%%", (100 * item.getFloat("lastvalue")) / 1024 / 1024 / base));
                        //object.put("base", base);
                        object.put("inbounditem", item.getString("itemid"));
                        itemids.add(itemid);  //后面查询使用
                        itemitemMap.put(itemid, key);
                        itemidHostidMap.put(itemid, hostid);
                    }
                }

                if (Pattern.matches(outKeyPattern, key)) { //item.getString("key_").equals(outkey)) {
                    String port = key.substring(
                            key.lastIndexOf("/")+1,
                            key.indexOf(":"));
                    String hostid = getHostidFromInterface(port, tags, nameHostidMap); //获取主机id
                    JSONObject object = result.get(hostid);
                    if(object != null) {
                        System.out.println(hostid+"_"+itemid+"_"+key + item.getString("lastvalue"));
                        Integer base = object.getInteger("base");
                        object.put("outbound", String.format("%.2f%%", (100 * item.getFloat("lastvalue")) / 1024 / 1024 / base));
                        object.put("outbounditem", item.getString("itemid"));

                        itemids.add(itemid);  //后面查询使用
                        itemitemMap.put(itemid, key);
                        itemidHostidMap.put(itemid, hostid);
                    }
                }
            }
        }


        //获取趋势数据
        filter.clear();
        filter.put("itemids", itemids);
        JSONArray trends = zabbixApi.trend_get(filter);

        HashMap<String,ArrayList<Float>> valueMap = new HashMap<>();
        for(Object _o: trends) {
            JSONObject trend = (JSONObject)_o;
            String itemid = trend.getString("itemid");
            String itemname = itemitemMap.get(itemid); //sec/in/out
            String key = String.format("%s_%s_%s", itemidHostidMap.get(itemid),itemid,itemname);
            ArrayList<Float> fList = valueMap.getOrDefault(key,new ArrayList<>());
            //fList.add(trend.getFloat("value_min"));
            //fList.add(trend.getFloat("value_max"));
            fList.add(trend.getFloat("value_avg"));
            valueMap.put(key,fList);
        }

        exportChinaDataToExcel(result, valueMap, new ArrayList<String>(sortedIds.values()), response,Long.valueOf(timestart),Long.valueOf(timeend));
    }


    /**
     * 获取非中国数据，本质上只有一个国家
     * @param filter
     * @return
     */
    private Map parseNotChinaData(HashMap<String,Object> filter,String hostid) {

        JSONArray array = zabbixApi.host_Get(filter);  //带ip

        JSONArray result = new JSONArray();
        Map<Integer,JSONObject> mapStatus1 = getStatus1Hosts(hostid);

        for(Object _hostObj: array) {

            JSONObject hostObj = (JSONObject) _hostObj;

            JSONObject object = new JSONObject();
            object.put("hostname",hostObj.getString("name"));
            object.put("hostid",hostObj.getString("hostid"));

            //可用性判断
            object.put("status",0); //正常
            JSONArray interfaces = hostObj.getJSONArray("interfaces");
            if(interfaces.size() > 0) {
                JSONObject interface0 = (JSONObject)(interfaces.get(0));
                if(interface0.getInteger("available") == 2) {
                    object.put("status", 2); //不可用
                } else {
                    if(mapStatus1.get(hostObj.getInteger("hostid")) != null) { //存在问题
                        object.put("status", 1); //存在问题
                    }
                }
                object.put("ip", interface0.getString("ip"));  //ip地址
                object.put("available", interface0.getString("available"));  //可用或不可用  1，2
            }
            //JSONObject net = new JSONObject();
            object.put("inbound","0.00%");
            object.put("outbound","0.00%");
            Integer base = getBandwidth(hostObj.getJSONArray("tags"));

            for(Object _obj: hostObj.getJSONArray("items")){
                JSONObject item = (JSONObject)_obj;
                if(item.getString("key_").equals("icmppingloss")) {
                    System.out.println("icmppingloss itemid:" + item.getString("itemid") + item.getString("lastvalue"));
                    object.put("icmppingloss", item.getString("lastvalue")+"%");
                }
                if(item.getString("key_").equals("icmppingsec")) {
                    System.out.println("icmppingsec itemid:" + item.getString("itemid") + item.getString("lastvalue"));
                    object.put("icmppingsec",String.format(("%.0fms"),item.getFloat("lastvalue")*1000));
                    object.put("icmppingsecitem", item.getString("itemid"));
                }
                String inkey = "net.if.in[ifInOctets.8]";
                if(item.getString("key_").equals(inkey)) {
                    System.out.println(item.getString("key_") + item.getString("lastvalue"));
                    object.put("inbound",String.format("%.2f%%", (100*item.getFloat("lastvalue"))/1024/1024/base));
                    object.put("inbounditem", item.getString("itemid"));
                }
                String outkey = "net.if.out[ifOutOctets.8]";
                if(item.getString("key_").equals(outkey)) {
                    System.out.println(item.getString("key_") + item.getString("lastvalue"));
                    object.put("outbound",String.format("%.2f%%", (100*item.getFloat("lastvalue"))/1024/1024/base));
                    object.put("outbounditem", item.getString("itemid"));
                }
            }

            result.add(object);
        }

        //filter.put("countOutput",true);
        Integer count = array.size(); //zabbixApi.host_get_count(filter);  //获取数量


        Map map = new HashMap();

        map.put("content", result);
        map.put("totalElements",count);

        map.put("isLast", true);  //是否最后一页
        map.put("page", 1);
        map.put("size", result.size());
        return map;
    }

    /**
     * 根据zabbix主机数据，封装主机信息
     * @param hostObj
     * @return
     */
    private JSONObject parseHostObject(JSONObject hostObj, Map<Integer,JSONObject> mapStatus1) {
        String host = hostObj.getString("host");  //专线名
        JSONObject object = new JSONObject();
        object.put("hostname",host);
        object.put("hostid",hostObj.getString("hostid"));
        object.put("tags", hostObj.getJSONArray("tags"));
        //可用性判断
        object.put("status",0); //正常
        JSONArray interfaces = hostObj.getJSONArray("interfaces");
        if(interfaces.size() > 0) {
            JSONObject interface0 = (JSONObject)(interfaces.get(0));
            if(interface0.getInteger("available") == 2) {
                object.put("status", 2); //不可用
            } else {
                if(mapStatus1.get(hostObj.getInteger("hostid")) != null) { //存在问题
                    object.put("status", 1); //存在问题
                }
            }
            object.put("ip", interface0.getString("ip"));  //ip地址
            object.put("available", interface0.getString("available"));  //可用或不可用  1，2
        }
        //JSONObject net = new JSONObject();
        for(Object _obj: hostObj.getJSONArray("items")){
            JSONObject item = (JSONObject)_obj;
            if(item.getString("key_").equals("icmppingloss")) {
                //System.out.println("icmppingloss itemid:" + item.getString("itemid") + item.getString("lastvalue"));
                object.put("icmppingloss", item.getString("lastvalue")+"%");
            }
            if(item.getString("key_").equals("icmppingsec")) {
                //System.out.println("icmppingsec itemid:" + item.getString("itemid") + item.getString("lastvalue"));
                object.put("icmppingsec", String.format("%.0fms", item.getFloat("lastvalue")*1000));
            }
            //System.out.println(item);
        }
        return object;
    }

    /**
     * 获取中国数据，本身不显示
     * @param filter
     * @param criteria
     * @return
     */
    private Map parseChinaData(HashMap<String,Object> filter, ZabbixQueryCriteria criteria) {
        Integer size = 10;
        if(criteria.getSize() != null) {
            size = criteria.getSize();
        }
        Integer page = 0;
        if(criteria.getPage() != null) {
            page = criteria.getPage();
        }
        filter.put("sortfield","host"); //排序
        filter.put("selectTags","extend");  //标识
        JSONArray array = zabbixApi.host_Get(filter);  //带ip

        Map<Integer,JSONObject> mapStatus1 = getStatus1Hosts(null);

        System.out.println(array.size());

        //中国的东西
        JSONObject chinaObj = null;
        HashMap<String,JSONObject> inMap = new HashMap<>(); //流量输入
        HashMap<String,JSONObject> outMap = new HashMap<>(); //流量输出
        HashMap<String,String> tagMap = new HashMap<>(); //标识
        SortedMap<Integer, JSONObject> sortedHostsMap = new TreeMap<>() ;
        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;
            String host = hostObj.getString("host");  //专线名
            if(host == null) {
                continue;
            }
            JSONObject object = parseHostObject(hostObj, mapStatus1); //这里不管取几个数据，都解析，为了ip排序
            String ip = object.getString("ip");
            sortedHostsMap.put(Integer.valueOf(ip.split("\\.")[3]), object);

            //从中国点开，获取的是中国的网卡对应的数据
            if(host.equalsIgnoreCase("China")){
                chinaObj = hostObj;
                for(Object _obj: hostObj.getJSONArray("items")) {
                    JSONObject item = (JSONObject)_obj;

                    String key =  item.getString("name");//item.getString("key_");
                    //if(key.startsWith("net.if.in[ifInOctets")) {
                    if(Pattern.matches(inKeyPattern,key)) {
                        inMap.put(key, item);
                        if(item.getFloat("lastvalue")>0) {
                            System.out.println(key + item.getString("lastvalue"));
                            System.out.println(item.toJSONString());
                        }
                    }
                    //if(key.startsWith("net.if.out[ifOutOctets")) {
                    if(Pattern.matches(outKeyPattern,key)) {
                        outMap.put(key, item);
                        if(item.getFloat("lastvalue")>0) {
                            System.out.println(key + item.getString("lastvalue"));
                            System.out.println(item.toJSONString());
                        }
                    }
                }
                for(Object _obj: hostObj.getJSONArray("tags")) {
                    JSONObject item = (JSONObject) _obj;
                    System.out.println(String.format("tag key:%s,value:%s",item.getString("tag"),item.getString("value")));
                    tagMap.put(item.getString("tag"),item.getString("value"));
                }
                // break;
            }
        }

        int count = array.size() > 0 ? array.size() - 1: 0;  //记录数量
        int i = 0;
        boolean isLast = false;
        JSONArray result = new JSONArray();
        for(Object _hostObj: sortedHostsMap.values().toArray()) {
            JSONObject object = (JSONObject) _hostObj;
            String host = object.getString("hostname");  //这里改成hostname
            if(i < page*size) {
                i++;
                continue;
            }
            i++;

            //封装数据
            object.put("inbound","0.00%");
            object.put("outbound","0.00%");
            if(host.equalsIgnoreCase("China")){
                object.put("inbound","-");
                object.put("outbound","-");
            } else {
                if(tagMap.get(host) != null) {
                    Integer base = getBandwidth(object.getJSONArray("tags"));
                    String inkey = inKeyPattern.replace("\\d+",tagMap.get(host));//String.format("net.if.in[ifInOctets.%s]",tagMap.get(host));
                    JSONObject in = inMap.get(inkey);
                    if(in != null) {
                        System.out.println(String.format("%s,%f",inkey,in.getFloat("lastvalue")));
                        object.put("inbound", String.format("%.2f%%", (100*in.getFloat("lastvalue"))/1024/1024/base));
                    }
                    String outkey = outKeyPattern.replace("\\d+",tagMap.get(host));//String.format("net.if.out[ifOutOctets.%s]",tagMap.get(host));
                    JSONObject out = outMap.get(outkey);
                    if(out != null) {
                        System.out.println(String.format("%s,%f",outkey,out.getFloat("lastvalue")));
                        object.put("outbound", String.format("%.2f%%", (100*out.getFloat("lastvalue"))/1024/1024/base));
                    }
                }
            }
            object.remove("tags");
            result.add(object);
            if(i == array.size()) {
                isLast = true;
            }
            if(result.size() >= size)
                break;
        }

        Map map = new HashMap();

        map.put("content", result);
        map.put("totalElements",count);

        map.put("isLast", isLast);  //是否最后一页
        map.put("page", page);
        map.put("size", result.size()); //每页数量
        return map;
    }

    /**
     * 获取宽带配置
     * @param array
     * @return
     */
    private Integer getBandwidth(JSONArray array) {
        if(array == null)
            return 10;

        try {
            for (Object _obj : array) {
                JSONObject tag = (JSONObject) _obj;
                if (tag.getString("tag").equals("bandwidth"))
                    return tag.getInteger("value");
            }
            return 10;
        }catch(Exception ex) {
            ex.printStackTrace();
            return 10;
        }
    }

    private JSONArray parseEvents(List<String> hostids, Long timestart, Long seconds) {
        JSONArray temp = new JSONArray();
        Map<String, JSONObject> r_eventids = new HashMap<>();
        int i = 1;
        HashMap<String,Object> filter = new HashMap<>();
        for(String hostid: hostids) {
            filter.clear();
            filter.put("hostids",hostid);
            // filter.put("time_from", timestart); ,时间范围内，未解决的要导出来
            filter.put("time_till", seconds);
            filter.put("sortfield", "eventid");

            JSONArray events = zabbixApi.event_get(filter);
            for (Object _o : events) {
                JSONObject obj = (JSONObject) _o;
                JSONObject re = new JSONObject();
                re.put("index",i++);
                re.put("hostid", hostid);
                re.put("name",obj.getString("name"));
                re.put("clock",obj.getLong("clock"));
                re.put("r_eventid",obj.getString("r_eventid"));
                //re.put("obj.getIntValue("r_eventid") > 0 ? "已处理" : "未处理");
                Integer value = obj.getIntValue("value");
                if(value > 0) {
                    temp.add(re);
                } else {
                    r_eventids.put(obj.getString("eventid"),obj);
                }
            }
        }
        JSONArray result = new JSONArray();
        for(Object _o: temp) {
            JSONObject obj = (JSONObject) _o;
            obj.put("duration", duration(obj.getLong("clock"), seconds));
            obj.put("status", "未解决");
            if(obj.getInteger("r_eventid") > 0) {
                JSONObject recovery = r_eventids.get(obj.getString("r_eventid"));
                if(recovery != null) {
                    if (r_eventids.get(obj.getString("r_eventid")) != null) {
                        obj.put("duration", duration(obj.getLong("clock"), recovery.getLong("clock")));
                        obj.put("status","已解决");
                        if(obj.getLong("clock") < timestart) {
                            continue; //如果问题已解决，且问题发生时间超出查询的周期，不导出
                        }
                    }
                }
            }
            result.add(obj);
        }
        return result;
    }

    /**
     *
     * @param data
     * @param valueMap
     * @param hostids
     * @param response
     * @param seconds 导出的截止时间
     */
    private void exportChinaDataToExcel(HashMap<String,JSONObject> data,
                                  HashMap<String,ArrayList<Float>> valueMap,
                                  List<String> hostids,
                                  HttpServletResponse response,
                                  Long timestart,
                                  Long seconds) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("主机信息");
        HSSFRow firstRow = sheet.createRow(0);
        firstRow.createCell(0).setCellValue("序号");
        firstRow.createCell(1).setCellValue("专线名");
        firstRow.createCell(2).setCellValue("专线IP");
        firstRow.createCell(3).setCellValue("丢包率");
        firstRow.createCell(4).setCellValue("时延");
        firstRow.createCell(5).setCellValue("时延最大值");
        firstRow.createCell(6).setCellValue("时延最小值");
        firstRow.createCell(7).setCellValue("inbound利用率");
        firstRow.createCell(8).setCellValue("inbound最大值");
        firstRow.createCell(9).setCellValue("inbound最小值");
        firstRow.createCell(10).setCellValue("outbound利用率");
        firstRow.createCell(11).setCellValue("outbound最大值");
        firstRow.createCell(12).setCellValue("outbound最小值");
        int i = 0 ;
        //for(Object _o: data) {

        for(Object _hostid: hostids) {
            String hostid = (String)_hostid;
            JSONObject obj = data.get(hostid);
            HSSFRow row = sheet.createRow(++i);
            row.createCell(0).setCellValue(String.valueOf(i));
            row.createCell(1).setCellValue(obj.getString("hostname"));
            row.createCell(2).setCellValue(obj.getString("ip"));
            row.createCell(3).setCellValue(obj.getString("icmppingloss"));
            row.createCell(4).setCellValue(obj.getString("icmppingsec"));
            if(obj.getString("hostname").equalsIgnoreCase("china")) {
                String icmppingsecitem = obj.getString("icmppingsecitem");
                String key = String.format("%s_%s_%s",hostid,icmppingsecitem,pingseckey);
                Float pingsecMin = valueMap.getOrDefault(key,new ArrayList<>()).stream().min(Comparator.comparing(p->p)).orElse(0f);
                Float pingsecMax = valueMap.getOrDefault(key,new ArrayList<>()).stream().max(Comparator.comparing(p->p)).orElse(0f);
                row.createCell(5).setCellValue(String.format(("%.0fms"), pingsecMax*1000));
                row.createCell(6).setCellValue(String.format(("%.0fms"), pingsecMin*1000));
                row.createCell(7).setCellValue("-");
                row.createCell(8).setCellValue("-");
                row.createCell(9).setCellValue("-");
                row.createCell(10).setCellValue("-");
                row.createCell(11).setCellValue("-");
                row.createCell(12).setCellValue("-");
            } else {
                //String hostid = obj.getString("hostid");
                String icmppingsecitem = obj.getString("icmppingsecitem");
                String inbounditem = obj.getString("inbounditem");
                String outbounditem = obj.getString("outbounditem");
                String key = String.format("%s_%s_%s",hostid,icmppingsecitem,pingseckey);
                Float pingsecMin = valueMap.getOrDefault(key,new ArrayList<>()).stream().min(Comparator.comparing(p->p)).orElse(0f);
                Float pingsecMax = valueMap.getOrDefault(key,new ArrayList<>()).stream().max(Comparator.comparing(p->p)).orElse(0f);
                key = String.format("%s_%s_%s",hostid,inbounditem, itemitemMap.get(inbounditem));
                System.out.println(key);
                Float inboundMin = valueMap.getOrDefault(key,new ArrayList<>()).stream().min(Comparator.comparing(p->p)).orElse(0f);
                Float inboundMax = valueMap.getOrDefault(key,new ArrayList<>()).stream().max(Comparator.comparing(p->p)).orElse(0f);
                key = String.format("%s_%s_%s",hostid,outbounditem, itemitemMap.get(outbounditem));
                System.out.println(key);
                Float outboundMin = valueMap.getOrDefault(key,new ArrayList<>()).stream().min(Comparator.comparing(p->p)).orElse(0f);
                Float outboundMax = valueMap.getOrDefault(key,new ArrayList<>()).stream().max(Comparator.comparing(p->p)).orElse(0f);

                Integer base = obj.getInteger("base");
                row.createCell(5).setCellValue(String.format(("%.0fms"), pingsecMax*1000));
                row.createCell(6).setCellValue(String.format(("%.0fms"), pingsecMin*1000));
                row.createCell(7).setCellValue(obj.getString("inbound"));
                row.createCell(8).setCellValue(String.format("%.2f%%", (100*inboundMax)/1024/1024/base));
                row.createCell(9).setCellValue(String.format("%.2f%%", (100*inboundMin)/1024/1024/base));
                row.createCell(10).setCellValue(obj.getString("outbound"));
                row.createCell(11).setCellValue(String.format("%.2f%%", (100*outboundMax)/1024/1024/base));
                row.createCell(12).setCellValue(String.format("%.2f%%", (100*outboundMin)/1024/1024/base));
            }
        }

        sheet = workbook.createSheet("问题列表");
        firstRow = sheet.createRow(0);
        firstRow.createCell(0).setCellValue("序号");
        firstRow.createCell(1).setCellValue("专线名");
        firstRow.createCell(2).setCellValue("问题告警信息");
        firstRow.createCell(3).setCellValue("告警发生时间");
        firstRow.createCell(4).setCellValue("告警持续时间");
        firstRow.createCell(5).setCellValue("当前状态");

        i = 0 ;
        //Long seconds = DateUtil.getUTCSeconds(DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));

        JSONArray events = parseEvents(hostids, timestart, seconds);
        for (Object _o : events) {
            JSONObject obj = (JSONObject) _o;
            HSSFRow row = sheet.createRow(++i);
            row.createCell(0).setCellValue(String.valueOf(i));
            row.createCell(1).setCellValue(hostidNameMap.getOrDefault(obj.getString("hostid"), ""));
            row.createCell(2).setCellValue(obj.getString("name")); //问题描述
            row.createCell(3).setCellValue(DateUtil.parseDateToStr(
                    new Date(obj.getLong("clock")*1000),
                    DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI)); //问题描述
            row.createCell(4).setCellValue(obj.getString("duration"));
            row.createCell(5).setCellValue(obj.getString("status"));
        }

        try {
            String realPath = "/tmp/chinahostreport.xls";
            OutputStream outputStream = new FileOutputStream(realPath);
            workbook.write(outputStream);

            response.setHeader("Content-Disposition", "attachment; filename="+"chinareport.xls");
            FileInputStream in = new FileInputStream(realPath);
            int len = 0;
            byte[] buffer = new byte[1024];
           //6.获取outputStream
            OutputStream out = response.getOutputStream();
            //将outputStream写入buffer缓冲区使用outputsream将缓冲区数据输入客户端
            while ((len=in.read(buffer))>0){
                out.write(buffer,0,len);
            }
            in.close();//记得关闭流
            out.close();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void processExcelData(JSONArray data,
                                  HashMap<String,ArrayList<Float>> valueMap,
                                  List<String> hostids,
                                  HttpServletResponse response,
                                  Long timestart,
                                  Long seconds) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("主机信息");
        HSSFRow firstRow = sheet.createRow(0);
        firstRow.createCell(0).setCellValue("序号");
        firstRow.createCell(1).setCellValue("专线名");
        firstRow.createCell(2).setCellValue("专线IP");
        firstRow.createCell(3).setCellValue("丢包率");
        firstRow.createCell(4).setCellValue("时延");
        firstRow.createCell(5).setCellValue("时延最大值");
        firstRow.createCell(6).setCellValue("时延最小值");
        firstRow.createCell(7).setCellValue("inbound利用率");
        firstRow.createCell(8).setCellValue("inbound最大值");
        firstRow.createCell(9).setCellValue("inbound最小值");
        firstRow.createCell(10).setCellValue("outbound利用率");
        firstRow.createCell(11).setCellValue("outbound最大值");
        firstRow.createCell(12).setCellValue("outbound最小值");
        int i = 0 ;
        for(Object _o: data) {
            JSONObject obj = (JSONObject)_o;
            HSSFRow row = sheet.createRow(++i);
            row.createCell(0).setCellValue(String.valueOf(i));
            row.createCell(1).setCellValue(obj.getString("hostname"));
            row.createCell(2).setCellValue(obj.getString("ip"));
            row.createCell(3).setCellValue(obj.getString("icmppingloss"));
            row.createCell(4).setCellValue(obj.getString("icmppingsec"));
            String hostid = obj.getString("hostid");
            String icmppingsecitem = obj.getString("icmppingsecitem");
            String inbounditem = obj.getString("inbounditem");
            String outbounditem = obj.getString("outbounditem");
            String key = String.format("%s_%s_%s",hostid,icmppingsecitem,pingseckey);
            Float pingsecMin = valueMap.getOrDefault(key,new ArrayList<>()).stream().min(Comparator.comparing(p->p)).orElse(0f);
            Float pingsecMax = valueMap.getOrDefault(key,new ArrayList<>()).stream().max(Comparator.comparing(p->p)).orElse(0f);
            key = String.format("%s_%s_%s",hostid,inbounditem, itemitemMap.get(inbounditem));
            Float inboundMin = valueMap.getOrDefault(key,new ArrayList<>()).stream().min(Comparator.comparing(p->p)).orElse(0f);
            Float inboundMax = valueMap.getOrDefault(key,new ArrayList<>()).stream().max(Comparator.comparing(p->p)).orElse(0f);
            key = String.format("%s_%s_%s",hostid,outbounditem, itemitemMap.get(outbounditem));
            Float outboundMin = valueMap.getOrDefault(key,new ArrayList<>()).stream().min(Comparator.comparing(p->p)).orElse(0f);
            Float outboundMax = valueMap.getOrDefault(key,new ArrayList<>()).stream().max(Comparator.comparing(p->p)).orElse(0f);

            Integer base = obj.getInteger("base");
            row.createCell(5).setCellValue(String.format(("%.0fms"), pingsecMax*1000));
            row.createCell(6).setCellValue(String.format(("%.0fms"), pingsecMin*1000));
            row.createCell(7).setCellValue(obj.getString("inbound"));
            row.createCell(8).setCellValue(String.format("%.2f%%", (100*inboundMax)/1024/1024/base));
            row.createCell(9).setCellValue(String.format("%.2f%%", (100*inboundMin)/1024/1024/base));
            row.createCell(10).setCellValue(obj.getString("outbound"));
            row.createCell(11).setCellValue(String.format("%.2f%%", (100*outboundMax)/1024/1024/base));
            row.createCell(12).setCellValue(String.format("%.2f%%", (100*outboundMin)/1024/1024/base));
        }

        sheet = workbook.createSheet("问题列表");
        firstRow = sheet.createRow(0);
        firstRow.createCell(0).setCellValue("序号");
        firstRow.createCell(1).setCellValue("专线名");
        firstRow.createCell(2).setCellValue("问题告警信息");
        firstRow.createCell(3).setCellValue("告警发生时间");
        firstRow.createCell(4).setCellValue("告警持续时间");
        firstRow.createCell(5).setCellValue("当前状态");
        i = 0 ;
        //Long seconds = DateUtil.getUTCSeconds(DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        JSONArray events = parseEvents(hostids, timestart, seconds);
        for (Object _o : events) {
            JSONObject obj = (JSONObject) _o;
            HSSFRow row = sheet.createRow(++i);
            row.createCell(0).setCellValue(String.valueOf(i));
            row.createCell(1).setCellValue(hostidNameMap.getOrDefault(obj.getString("hostid"), ""));
            row.createCell(2).setCellValue(obj.getString("name")); //问题描述
            row.createCell(3).setCellValue(DateUtil.parseDateToStr(
                    new Date(obj.getLong("clock")*1000),
                    DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI)); //问题描述
            row.createCell(4).setCellValue(obj.getString("duration"));
            row.createCell(5).setCellValue(obj.getString("status"));
        }

        try {
            String realPath = "/tmp/hostreport.xls";
            OutputStream outputStream = new FileOutputStream(realPath);
            workbook.write(outputStream);

            response.setHeader("Content-Disposition", "attachment; filename="+"hostreport.xls");
            FileInputStream in = new FileInputStream(realPath);
            int len = 0;
            byte[] buffer = new byte[1024];
            //6.获取outputStream
            OutputStream out = response.getOutputStream();
            //将outputStream写入buffer缓冲区使用outputsream将缓冲区数据输入客户端
            while ((len=in.read(buffer))>0){
                out.write(buffer,0,len);
            }
            in.close();//记得关闭流
            out.close();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private String duration(Long start, Long end) {
        Long duration = end - start ;
        if(duration < 60) {
            return "0m";
        } else if(3600 > duration && duration >= 60) {
          return String.format("%dm", (int)(duration/60F));
        } else if(3600*24 > duration && duration >= 3600) {
            return String.format("%dh%dm",duration/3600, (duration%3600)/60);
        } else {
            return String.format("%dd%dh%dm",duration/3600/24, (duration%(3600*24))/3600, (duration%3600)/60);
        }
    }

    /**
     * 主机获取，如果是中国，则获取中国出口关联的其他信息
     * @param criteria
     * @return
     */
    @GetMapping(value = "/zabbix/host/export")
    public ResponseEntity hostExport(ZabbixQueryCriteria criteria,HttpServletResponse response) {
        try{
            HashMap<String,Object> filter = new HashMap<String,Object>();

            Long seconds = DateUtil.getUTCSeconds(DateUtil.parseDateToStr(new Date(),
                    DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
            Long start = DateUtil.getUTCSeconds(DateUtil.parseDateToStr(
                    DateUtil.monthCal(new Date(),Calendar.MONTH,-1),
                    DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
            if(StringUtils.isEmpty(criteria.getTimeend())) {
                criteria.setTimeend(String.valueOf(seconds));
                criteria.setTimestart(String.valueOf(start));
            }

            if(StringUtils.isEmpty(criteria.getTimestart())) {
                criteria.setTimestart(String.valueOf(start));
            }

            filter.put("selectInterfaces","extend");
            filter.put("selectItems","extend"); //
            filter.put("selectTags","extend"); //
            filter.put("selectInventory",true); //资产
            JSONObject fObj = new JSONObject(); fObj.put("type",2); //snmp,其它不取
            filter.put("filter", fObj);

            JSONObject data = new JSONObject();
            if(!StringUtils.isEmpty(criteria.getHostids())){
                if(!criteria.getHostids().equals(chinaid)) {  //中国id,获取全部主机数量
                    filter.put("hostids", criteria.getHostids().split(","));
                    processNotChinaHisDataWithoutPage(filter,criteria.getHostids(),
                            criteria.getTimestart(),criteria.getTimeend(),
                            response);
                } else {
                    processChinaHisDataWithoutPage(filter,
                            criteria.getTimestart(),
                            criteria.getTimeend(),
                            response);
                }
            }

            JSONObject entiry = new JSONObject();
            entiry.put("status", HttpStatus.OK.value());
            entiry.put("data",data);
            return new ResponseEntity(entiry, HttpStatus.OK);
        } catch(Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse("内部错误",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 主机获取，如果是中国，则获取中国出口关联的其他信息
     * @param criteria
     * @return
     */
    @GetMapping(value = "/zabbix/host/get")
    public ResponseEntity hostGet(ZabbixQueryCriteria criteria) {
        try{
        HashMap<String,Object> filter = new HashMap<String,Object>();

        filter.put("selectInterfaces","extend");
        filter.put("selectItems","extend"); //
        filter.put("selectInventory",true); //资产
        JSONObject fObj = new JSONObject(); fObj.put("type",2); //snmp,其它不取
        filter.put("filter", fObj);


        Map map = new HashMap();
        if(!StringUtils.isEmpty(criteria.getHostids())){
            if(!criteria.getHostids().equals(chinaid)) {  //中国id,获取全部主机数量
                filter.put("hostids", criteria.getHostids().split(","));
                 map = parseNotChinaData(filter,criteria.getHostids());
            } else {
                map = parseChinaData(filter,criteria);
            }
        }

        JSONObject entiry = new JSONObject();
        entiry.put("status", HttpStatus.OK.value());
        entiry.put("data",map);
        return new ResponseEntity(entiry, HttpStatus.OK);
        } catch(Exception ex) {
            ex.printStackTrace();
            return HttpResponseUtils.passDefaultResponse("内部错误",HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @GetMapping(value = "/zabbix/problem/get")
    public ResponseEntity problemGet(ZabbixQueryCriteria criteria) {
        HashMap<String,Object> filter = new HashMap<String,Object>();


        if(!StringUtils.isEmpty(criteria.getHostids())){
            filter.put("hostids", criteria.getHostids().split(","));
        } else {
            filter.put("hostids", "0");  //不查询
        }
        filter.put("sortfield","eventid"); //排序

        Integer size = 10;
        if(criteria.getSize() != null) {
            size = criteria.getSize();
        }
        Integer page = 0;
        if(criteria.getPage() != null) {
            page = criteria.getPage();
        }
        filter.put("limit", (page+1)*size); //每页数量

        JSONArray array = zabbixApi.problem_get(filter);  //带ip

        Long seconds = DateUtil.getUTCSeconds(DateUtil.parseDateToStr(new Date(), DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        JSONArray result = new JSONArray();
        int i = 0;
        for(Object _hostObj: array) {
            if(i++ < page*size)
                continue; //@@@@@TODO 后续支持自动分页，否则全部查询，去掉前面几页，i++一次
            if(i >= (page+1)*size)
                break;

            JSONObject hostObj = (JSONObject) _hostObj;
            JSONObject object = new JSONObject();
            object.put("problem",hostObj.getString("name"));
            object.put("index",i);
            object.put("duration", duration(hostObj.getLong("clock"), seconds));
            result.add(object);
        }

        filter.put("countOutput",true);
        Integer count = array.size();  //zabbixApi.problem_get_count(filter);  //获取数量

        Map map = new HashMap();

        map.put("content", result);
        map.put("totalElements",count);

        map.put("isLast", (page+1)*size >= count);  //是否最后一页
        map.put("page", page);
        map.put("size", size);

        JSONObject entiry = new JSONObject();
        entiry.put("status", HttpStatus.OK.value());
        entiry.put("data",map);
        return new ResponseEntity(entiry, HttpStatus.OK);
    }


    @GetMapping(value = "/zabbix/graph/get")
    public ResponseEntity graphGet(ZabbixQueryCriteria criteria) {
        HashMap<String,Object> filter = new HashMap<String,Object>();

        if(!StringUtils.isEmpty(criteria.getHostids())){
            filter.put("hostids",criteria.getHostids().split(","));
        }
        filter.put("selectHosts","extend"); //加组信息

        JSONArray result = new JSONArray();
        JSONArray array = zabbixApi.graph_get(filter);

        for(Object _hostObj: array) {
            JSONObject hostObj = (JSONObject) _hostObj;
            JSONObject object = new JSONObject();
            object.put("graphname",hostObj.getString("name"));
            object.put("graphid",hostObj.getString("graphid"));
            result.add(object);
        }

        return new ResponseEntity(result, HttpStatus.OK);
    }

    @GetMapping(value = "/zabbix/graph/image")
    public ResponseEntity graphImage(HttpServletRequest request, HttpServletResponse response) {
        Map<String,String> params = new HashMap<String,String>();
        if(!StringUtils.isEmpty(request.getParameter("graphId")))
            params.put("graphId",request.getParameter("graphId"));

        if(StringUtils.isEmpty(request.getParameter("period"))) {
            params.put("period", "86400");
        }else{
            params.put("period",request.getParameter("period"));
        }

        if(StringUtils.isEmpty(request.getParameter("stime"))) {
            params.put("stime", DateUtil.parseDateToStr(new Date(System.currentTimeMillis()-86400*1000),DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS));
        }else{
            params.put("stime",request.getParameter("stime"));
        }


        CloseableHttpResponse res = zabbixApi.graphImage(params);
        try{
            if(res != null) {
                response.setContentType("application/octet-stream");
                ServletOutputStream out = response.getOutputStream();
                InputStream in = res.getEntity().getContent();
                byte[] tmp = new byte[1024];
                int a = -1;
                while ((a = in.read(tmp)) != -1) {
                    out.write(tmp, 0, a);
                }
                out.flush();
                out.close();
                in.close();
            }
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return ResponseEntity.ok().build();
    }

    @GetMapping(value = "/zabbix/trigger/get")
    public ResponseEntity triggerGet() {
        return new ResponseEntity(zabbixApi.trigger_Get(new HashMap<String,Object>()), HttpStatus.OK);
    }

    @GetMapping(value = "/zabbix/dashboard/hoststat/get")
    public ResponseEntity dashboardHoststatGet() {
        return new ResponseEntity(zabbixApi.dashboard_HoststatGet(new HashMap<String,Object>()), HttpStatus.OK);
    }
}
